package com.sky.interceptor;

import com.sky.context.BaseContext;
import com.sky.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class JwtTokenAdminInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}",requestURI);
//        if (!(handler instanceof HandlerMethod)) {
//            //当前拦截到的不是动态方法，直接放行
//            log.info("当前请求不需要处理");
//            return true;
//        }

        if (requestURI.contains("login")) {
            return true;
        }
        String token=request.getHeader("token");
        if (token==null|| token.isEmpty()){
            log.info("用户未登录");
            response.setStatus(401);
            return false;
        }
        try {
            Claims claims = JwtUtils.parseJwt(token);
            Object empId = claims.get("empId");
            BaseContext.setCurrentId(Long.valueOf(empId.toString()));
            log.info("当前用户id为：{}",empId);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            log.info("token被篡改");
            response.setStatus(403);
            return false;
        }
        log.info("token没问题");
        return true;
    }
}
